//
//  SMHomeViewController.m
//  ShoppingMall
//
//  Created by Demon on 2018/3/21.
//  Copyright © 2018年 Demon. All rights reserved.
//

#import "SMHomeViewController.h"
#import "SMHomeTableViewCell.h"
#import "SMProductListViewController.h"
#import "SMHomeModel.h"
#import "SMHomeHeadTableViewCell.h"
#import "YDWebViewController.h"
#import "SMHomeMiddleTableViewCell.h"
#import <HTHorizontalSelectionList.h>
#import "SMPrdDetailViewController.h"

@interface SMHomeViewController () <UITableViewDataSource, UITableViewDelegate, SMHomeCellProtocol, HTHorizontalSelectionListDelegate, HTHorizontalSelectionListDataSource>
{
    NSInteger page;
    NSString *menuUrl;
}
@property (weak, nonatomic) IBOutlet UITableView *homeTableView;
@property (nonatomic, strong) SMHomeModel *homeModel;
@property (nonatomic, strong) HTHorizontalSelectionList *horiSelectListView;
@property (nonatomic, strong) UILabel *wonderfulLabel;
@property (nonatomic, strong) NSMutableArray <SMProductModel *>*prdListArray;

@end

@implementation SMHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.homeTableView registerNib:[UINib nibWithNibName:NSStringFromClass([SMHomeTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SMHomeTableViewCell"];
    [self.homeTableView registerNib:[UINib nibWithNibName:NSStringFromClass([SMHomeHeadTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SMHomeHeadTableViewCell"];
    [self.homeTableView registerNib:[UINib nibWithNibName:[SMHomeMiddleTableViewCell className] bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SMHomeMiddleTableViewCell"];
    self.homeTableView.estimatedRowHeight = 0;
    page = 1;
    [self getHomeDataRequest];
    
    [self.homeTableView addHeadFresh:self selector:@selector(headerFresh)];
    MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerFresh)];
    refreshFooter.automaticallyChangeAlpha = YES;
    self.homeTableView.mj_footer = refreshFooter;
}

- (void)headerFresh {
    page = 1;
    [self.homeTableView.mj_footer resetNoMoreData];
    [self getHomeDataRequest];
}

- (void)footerFresh {
    page ++;
    [self getHaoqQuanZhiBoData];
}

- (void)getHomeDataRequest {
    [[YDNetClient sharedInstance] getMethod:@"http://jidianping.com/api/tb/goods.php" param:nil success:^(id object) {
        self.homeModel = [SMHomeModel mj_objectWithKeyValues:object];
        [self.homeTableView reloadData];
        [self.horiSelectListView reloadData];
        SMCateModel *cateModel = self.homeModel.cate[self.horiSelectListView.selectedButtonIndex];
        menuUrl = cateModel.menuUrl;
        [self getHaoqQuanZhiBoData];
    } fail:^(NSError *error) {
        [self.homeTableView endFresh];
    }];
}

- (void)getHaoqQuanZhiBoData {
    NSString *pageNumber = [NSString stringWithFormat:@"%ld",(long)page];
    [[YDNetClient sharedInstance] getMethod:[NSString stringWithFormat:@"%@&page=%@",menuUrl,pageNumber] param:nil success:^(id object) {
        [self.homeTableView endFresh];
        if (page == 1) [self.prdListArray removeAllObjects];
        NSArray *dicArray = object[@"listData"];
        NSArray *array = [SMProductModel mj_objectArrayWithKeyValuesArray:dicArray];
        if (array.count > 0) {
            [self.prdListArray addObjectsFromArray:array];
        } else {
            [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
            if (page > 1) page --;
        }
        [self.homeTableView reloadSection:1 withRowAnimation:UITableViewRowAnimationNone];
    } fail:^(NSError *error) {
        [self.homeTableView endFresh];
        if (page > 1) page --;
    }];
}

#pragma mark - SMHomeCellProtocol

- (void)homeCellWithName:(NSString *)name h5url:(NSString *)h5url dataurl:(NSString *)dataurl {
    if (dataurl && dataurl.length > 0) {
        SMProductListViewController *prdListVC = MainStoryBoardVC(@"SMProductListViewController");
        prdListVC.dataurl = dataurl;
        prdListVC.navigationItem.title = name;
        [self.navigationController pushViewController:prdListVC animated:YES];
    } else if (h5url && h5url.length > 0) {
        YDWebViewController *webVC = ALLOC(YDWebViewController);
        webVC.webUrl = h5url;
        webVC.navigationItem.title = name;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

#pragma mark - tableviewdelgate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section  == 1) {
        SMPrdDetailViewController *detailVC = MainStoryBoardVC([SMPrdDetailViewController className]);
        SMProductModel *prdModel = self.prdListArray[indexPath.row];
        detailVC.prdId = prdModel.pid;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma mark - horilistDelegate

- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index {
    SMCateModel *cateModel = self.homeModel.cate[index];
    page = 1;
    menuUrl = cateModel.menuUrl;
    [self getHaoqQuanZhiBoData];
}

#pragma mark - datasource

- (NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList {
    return self.homeModel.cate.count;
}

- (nullable NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index {
    NSArray *titles = [self.homeModel.cate valueForKeyPath:@"menuName"];
    return titles[index];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) return 2;
    return self.prdListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            SMHomeHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMHomeHeadTableViewCell" forIndexPath:indexPath];
            cell.delegate = self;
            [cell setHeadCellModel:self.homeModel];
            return cell;
        } else {
            SMHomeMiddleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMHomeMiddleTableViewCell" forIndexPath:indexPath];
            cell.delegate = self;
            [cell setHomeMiddleCellModel:self.homeModel.brands];
            return cell;
        }
    } else {
        SMHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMHomeTableViewCell" forIndexPath:indexPath];
        cell.indexPathCell = indexPath;
        cell.shareBtnClick = ^(NSIndexPath *indexPathCell) {
            [self tableView:tableView didSelectRowAtIndexPath:indexPathCell];
        };
        [cell setHomeTableViewModel:self.prdListArray[indexPath.row]];
        return cell;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) return ALLOC(UIView);
    UIView *secntionView = ALLOC(UIView);
    [secntionView addSubview:self.wonderfulLabel];
    [secntionView addSubview:self.horiSelectListView];
    return secntionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) return 0.0000001;
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return SCREEN_RATIO_CEIL(375);
        }
        return SCREEN_RATIO_CEIL(314);
    }
    return 124;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return ALLOC(UIView);
}

- (NSMutableArray<SMProductModel *> *)prdListArray {
    if (!_prdListArray) {
        _prdListArray = [NSMutableArray array];
    }
    return _prdListArray;
}

- (HTHorizontalSelectionList *)horiSelectListView {
    if (!_horiSelectListView) {
        _horiSelectListView = [[HTHorizontalSelectionList alloc] initWithFrame:CGRectMake(0, 35, kScreenW, 45)];
        _horiSelectListView.dataSource = self;
        _horiSelectListView.delegate = self;
        _horiSelectListView.backgroundColor = UIColorHex(ffffff);
        _horiSelectListView.showsEdgeFadeEffect = YES;
        [_horiSelectListView setTitleFont:UIFONTSIZE(15) forState:UIControlStateNormal];
        [_horiSelectListView setTitleFont:UIFONTSIZE(15) forState:UIControlStateSelected];
        [_horiSelectListView setTitleColor:UIColorHex(33333) forState:UIControlStateNormal];
        [_horiSelectListView setTitleColor:UIColorHex(FFAA1A) forState:UIControlStateSelected];
        _horiSelectListView.bottomTrimColor = UIColorHex(eaeaea);
        _horiSelectListView.selectionIndicatorColor = UIColorHex(FFAA1A);
        _horiSelectListView.snapToCenter = YES;
    }
    return _horiSelectListView;
}

- (UILabel *)wonderfulLabel {
    if (!_wonderfulLabel) {
        _wonderfulLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 35)];
        _wonderfulLabel.backgroundColor = UIColorHex(ffffff);
        _wonderfulLabel.textColor = UIColorHex(FFAA1A);
        _wonderfulLabel.text = @"限时优惠商品推荐";
        _wonderfulLabel.font = UIFONTSIZE(18);
        _wonderfulLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _wonderfulLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
